package com.chookss.home.update;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;

public class UpdateService extends Service {
    public static int NotificationId = 4;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        KLog.i("onStartCommand: 下载开始");
        initNotification();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = intent.getStringExtra("url");
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                ;
                download(url, fileName);
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification( GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "down_apk_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已下载"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    private void download(String url, String fileName) {
        MyApp.isDownApk = true;
        Intent intent = new Intent();
        intent.setPackage(getPackageName());
        intent.setAction("downApk");
        OkGo.<File>get(url).execute(new FileCallback(getExternalFilesDir(Urls.APKFOLDER).getAbsolutePath(), fileName) {
            int currentPercent = 0;
            @Override
            public void downloadProgress(Progress progress) {
                currentPercent = (int) (progress.fraction * 100);
                Message msg = handler.obtainMessage();
                msg.arg1 = currentPercent;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Response<File> response) {
                MyToast.show("下载更新文件失败");
                MyApp.isDownApk = false;
                stopSelf();
                currentPercent = 0;
            }

            @Override
            public void onSuccess(Response<File> response) {
                MyApp.isDownApk = false;
                intent.putExtra("percent", 100);
                intent.putExtra("fileName", fileName);
                LocalBroadcastManager.getInstance(UpdateService.this).sendBroadcast(intent);
                Message msg = handler.obtainMessage();
                msg.arg1 = 100;
                handler.sendMessage(msg);
                stopSelf();
            }

        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}